package com.zz.framework.core.base

import android.os.Bundle
import android.view.View
import androidx.annotation.Nullable
import com.zz.framework.core.base.BaseViewModelFragment

/**
 * Copyright © 2020 zanezhao All rights reserved.
 * Created on 2020/3/18 11:05 AM.
 * @version: V1.0
 */
abstract class BaseLazyFragment: BaseViewModelFragment() {
    protected var isVisiblity = false
    protected var isPrepared = false // 标志位，标志已经初始化完成。
    /**
     * 是否已被加载过一次，第二次就不再去请求数据
     */
    private var mHasLoaded = false

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (userVisibleHint) {
            isVisiblity = true
            onVisible()
        } else {
            isVisiblity = false
            onInVisible()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isPrepared = true
    }

    override fun onActivityCreated(@Nullable savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        onVisible()
    }

    protected fun isLazyLoad(): Boolean {
        return !(!isPrepared || !isVisiblity || mHasLoaded)
    }

    open protected fun onVisible() {
        if (isLazyLoad()) lazyLoad()
        if (!(!isPrepared || !isVisiblity)) lazyAlwaysLoad()
    }

    open protected fun onInVisible() {
    }

    abstract fun lazyLoad()

    open fun lazyAlwaysLoad(){}

    fun isHasLoaded(): Boolean {
        return mHasLoaded
    }

    fun setHasLoaded(hasLoaded: Boolean) {
        mHasLoaded = hasLoaded
    }

}